/*
	The MIT License

	Copyright (c) 2010 IFMO/GameDev Studio

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/

#include "rs_local.h"
#include "i_rs_driver.h"
#include "dbg_scene.h"


IDVScene	*CreateDVScene	( ERenderSystem *rs ) { return new EDVScene(rs); }

EDVScene	*EDVScene::self = NULL;
																		
/*-----------------------------------------------------------------------------
	Debug scene :
-----------------------------------------------------------------------------*/

//
//	EDVScene::EDVScene
//
EDVScene::EDVScene( ERenderSystem *rs )
{
	this->rs	=	rs;
	driver		=	rs->Driver();
	fxm			=	driver->GetFXM();
	vbm			=	driver->GetVBM();
	self		=	this;
	
	current_color	=	EColor::kWhite;

	InitLuaAPI();

	LOG_INIT("Debug scene");
	
	lines.reserve(1000);
	
	ReloadShaders();
}


//
//	EDVScene::~EDVScene
//
EDVScene::~EDVScene( void )
{
	LOG_SHUTDOWN("Debug scene");
}


//
//	EDVScene::ReloadShaders
//
void EDVScene::ReloadShaders( void )
{
	effect	=	fxm->CompileEffect("shaders/debug.cgfx");
}


//
//	EDVScene::SetView
//
void EDVScene::SetView( const EPoint &position, const EQuaternion &orient )
{
	this->position		=	position;

	EMatrix	T		=	EMatrix::Translate( -EVector(position) );
	EMatrix	R		=	orient.Inverse().ToMatrix();

	matrix_view	=	T * R;	
}


//
//	EDVScene::SetProjection
//
void EDVScene::SetProjection( float znear, float zfar, float width, float height )
{
	float w = znear * width  / zfar;
	float h = znear * height / zfar;
	
	matrix_proj	=	EMatrix::PerspectiveRH(w, h, znear, zfar);
}


//
//	EDVScene::DrawLine
//
void EDVScene::DrawLine( const ERSLine_s &line )
{
	ERSLine_s	line_trans;
	
	line_trans		=	line;
	line_trans.v0	=	line.v0.Transform(matrix_world);
	line_trans.v1	=	line.v1.Transform(matrix_world);
	
	lines.push_back( line_trans );
}


//
//	EDVScene::RenderScene
//
void EDVScene::RenderScene( void )
{
	while (!matrix_stack.empty()) {
		matrix_stack.pop();
	}

	lines.reserve( lines.size() );
	
	if (lines.empty()) {
		return;
	}
	
	if (!effect) {
		lines.clear();
		return;		
	}
	
	effect->SetTechnique("tech_debug");
	
	effect->SetUniform("matrix_view", matrix_view );
	effect->SetUniform("matrix_proj", matrix_proj );

	uint n;	
	effect->Begin(n);
	
		for (uint i=0; i<n; i++) {
		
			effect->BeginPass(i);
		
			vbm->DrawLines( lines.size(), &lines[0] );
			
			effect->EndPass();
		}		

	effect->End();

	lines.clear();
}


//
//	EDVScene::PushWorldMatrix
//
void EDVScene::PushWorldMatrix( void )
{
	matrix_stack.push( matrix_world );
}


//
//	EDVScene::MulWorldMatrix
//
void EDVScene::MulWorldMatrix( const EMatrix world )
{
	matrix_world	=	matrix_world * world;
}


//
//	EDVScene::MulWorldMatrix
//
void EDVScene::MulWorldMatrix( const EPoint &position, const EQuaternion &orient )
{
	MulWorldMatrix( EMatrix::FromPose( position, orient ) );
}


//
//	EDVScene::PopWorldMatrix
//
void EDVScene::PopWorldMatrix( void )
{
	matrix_world	=	matrix_stack.top();
	matrix_stack.pop();
}


/*-----------------------------------------------------------------------------
	Primitives :
-----------------------------------------------------------------------------*/

//
//	EDVScene::DrawPoint
//
void EDVScene::DrawPoint( const EPoint &origin, float size, const EColor &color )
{
	ERSLine_s	line;
	
	float	s	=	size / 2;

	line.c0		=	line.c1		=	color;
	line.uv0	=	line.uv1	=	ETexCoord(0,0);

	line.v0		=	origin + EVector(+s, 0, 0);
	line.v1		=	origin + EVector(-s, 0, 0);
	DrawLine( line );	 

	line.v0		=	origin + EVector( 0,+s, 0);
	line.v1		=	origin + EVector( 0,-s, 0);
	DrawLine( line );	 

	line.v0		=	origin + EVector( 0, 0,+s);
	line.v1		=	origin + EVector( 0, 0,-s);
	DrawLine( line );	 
}


//
//	EDVScene::DrawArrow
//
void EDVScene::DrawArrow( const EPoint &origin, const EVector &dir, float scale, const EColor &color )
{
	ERSLine_s	line;

	line.c0			=	line.c1		=	color;
	line.uv0		=	line.uv1	=	ETexCoord(0,0);
	
	line.v0			=	origin;
	line.v1			=	origin + dir * scale;
	DrawLine( line );	 
	
	//	tip :
	float	len		=	dir.Length();
	EPoint	vp		=	position;	
	EPoint	tip		=	origin + dir * scale * 1.0f;
	EPoint	org		=	origin + dir * scale * 0.85f;
	EVector	vd		=	EVector(vp) - EVector(org);
	EVector	side	=	EMath::Cross( dir, vd ).Normalize();
	EVector	right	=	side * len * (-0.02f) * scale;

	line.v0			=	tip;
	line.v1			=	org + right;
	DrawLine( line );	 
	
	line.v0			=	tip;
	line.v1			=	org - right;
	DrawLine( line );	 
	
}


//
//	EDVScene::DrawBox
//
void EDVScene::DrawBox( const EBBox &bbox, const EColor &color )
{
	ERSLine_s	line;

	line.c0			=	line.c1		=	color;
	line.uv0		=	line.uv1	=	ETexCoord(0,0);
	
	EPoint	pmax	=	bbox.Max();
	EPoint	pmin	=	bbox.Min();
	
	EPoint	p[8];
	p[0]	=	EPoint	(	pmax.x, pmax.y, pmax.z	);
	p[1]	=	EPoint	(	pmax.x, pmin.y, pmax.z	);
	p[2]	=	EPoint	(	pmin.x, pmin.y, pmax.z	);
	p[3]	=	EPoint	(	pmin.x, pmax.y, pmax.z	);

	p[4]	=	EPoint	(	pmax.x, pmax.y, pmin.z	);
	p[5]	=	EPoint	(	pmax.x, pmin.y, pmin.z	);
	p[6]	=	EPoint	(	pmin.x, pmin.y, pmin.z	);
	p[7]	=	EPoint	(	pmin.x, pmax.y, pmin.z	);
	
	line.v0	=	p[0];	line.v1	=	p[1];		DrawLine( line );
	line.v0	=	p[1];	line.v1	=	p[2];		DrawLine( line );
	line.v0	=	p[2];	line.v1	=	p[3];		DrawLine( line );
	line.v0	=	p[3];	line.v1	=	p[0];		DrawLine( line );
	
	line.v0	=	p[4];	line.v1	=	p[5];		DrawLine( line );
	line.v0	=	p[5];	line.v1	=	p[6];		DrawLine( line );
	line.v0	=	p[6];	line.v1	=	p[7];		DrawLine( line );
	line.v0	=	p[7];	line.v1	=	p[4];		DrawLine( line );
	
	line.v0	=	p[0];	line.v1	=	p[4];		DrawLine( line );
	line.v0	=	p[1];	line.v1	=	p[5];		DrawLine( line );
	line.v0	=	p[2];	line.v1	=	p[6];		DrawLine( line );
	line.v0	=	p[3];	line.v1	=	p[7];		DrawLine( line );
}


/*-----------------------------------------------------------------------------
	Lua stuff :
-----------------------------------------------------------------------------*/

//
//	EDVScene::InitLuaAPI
//
void EDVScene::InitLuaAPI( void )
{
	lua_State *L = CoreLua();
	
	LUALIB_DECLARE	("dv")
	LUALIB_METHOD	( setColor	)
	LUALIB_METHOD	( drawLine	)
	LUALIB_METHOD	( drawArrow	)
	LUALIB_METHOD	( drawPoint	)
	LUALIB_METHOD	( drawBox	)
	LUALIB_REGISTER	( L )
}


//
//	EDVScene::setColor
//
int EDVScene::setColor( lua_State *L )
{
	LUA_INTERFACE(L);

	float a = 1.0f;

	float r = lua.RequireNumber(1, "r");
	float g = lua.RequireNumber(2, "g");
	float b = lua.RequireNumber(3, "b");

	if (lua_gettop(L) > 3)
	{
		a = lua.RequireNumber(4, "a");
	}

	self->current_color = EColor(r, g, b, a);

	return 0;
}


//
//	EDVScene::drawLine
//
int EDVScene::drawLine( lua_State *L )
{
	LUA_INTERFACE(L);

	float x1 = lua.RequireNumber(1, "x1");
	float y1 = lua.RequireNumber(2, "y1");
	float z1 = lua.RequireNumber(3, "z1");
	float x2 = lua.RequireNumber(4, "x2");
	float y2 = lua.RequireNumber(5, "y2");
	float z2 = lua.RequireNumber(6, "z2");
	ERSLine_s line;

	line.v0 = EPoint(x1, y1, z1);
	line.v1 = EPoint(x2, y2, z2);

	line.c0 = self->current_color;
	line.c1 = self->current_color;

	line.uv0 = ETexCoord(0,0);
	line.uv1 = ETexCoord(1,1);

	self->DrawLine(line);

	return 0;
}


//
//	EDVScene::drawArrow
//
int EDVScene::drawArrow( lua_State *L )
{
	LUA_INTERFACE(L);

	float x1 = lua.RequireNumber(1, "x1");
	float y1 = lua.RequireNumber(2, "y1");
	float z1 = lua.RequireNumber(3, "z1");
	float dx = lua.RequireNumber(4, "dx");
	float dy = lua.RequireNumber(5, "dy");
	float dz = lua.RequireNumber(6, "dz");
	float s  = lua.RequireNumber(7, "s");

	self->DrawArrow(EPoint(x1, y1, z1), EVector(dx, dy, dz), s, self->current_color);

	return 0;
}


//
//	EDVScene::drawPoint
//
int EDVScene::drawPoint( lua_State *L )
{
	LUA_INTERFACE(L);

	float x1 = lua.RequireNumber(1, "x1");
	float y1 = lua.RequireNumber(2, "y1");
	float z1 = lua.RequireNumber(3, "z1");
	float  s = lua.RequireNumber(4, "s");

	self->DrawPoint(EPoint(x1, y1, z1), s, self->current_color);

	return 0;
}


//
//	EDVScene::drawBox
//
int EDVScene::drawBox( lua_State *L )
{
	LUA_INTERFACE(L);

	float x1 = lua.RequireNumber(1, "x1");
	float y1 = lua.RequireNumber(2, "y1");
	float z1 = lua.RequireNumber(3, "z1");
	float x2 = lua.RequireNumber(4, "x2");
	float y2 = lua.RequireNumber(5, "y2");
	float z2 = lua.RequireNumber(6, "z2");

	EBBox box(EPoint(x1, y1, z1), EPoint(x2, y2, z2));

	self->DrawBox(box, self->current_color);

	return 0;
}
